//
//  LSBecomeVIPVC.m
//  HappyStore
//
//  Created by 陈锋 on 16/8/10.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "LSBecomeVIPVC.h"
#import "LSCustomBtn.h"
#import "LSPayResultVC.h"
#import "LSRechargeVC.h"
@interface LSBecomeVIPVC (){

    double price;
    double balanceLabel;
    NSInteger payWay;
    NSInteger orderNumber;
    NSString * productBody;
    NSString * order_no;

}

@property (strong, nonatomic) NSArray * dataArr;
@property (strong, nonatomic) UIButton * selectedBtn;
@property (strong, nonatomic) UILabel * moneyLabel;
@property (weak, nonatomic) IBOutlet UILabel *cashLabel;
@property (weak, nonatomic) IBOutlet UIButton *payBtn;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UILabel *balanceLabel;
@property (weak, nonatomic) IBOutlet UIView *balanceView;

@end

@implementation LSBecomeVIPVC

-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentView) name:@"alipayResult" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentFailedView) name:@"alipayFailed" object:nil];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"白色背景"] forBarMetrics:UIBarMetricsDefault];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}
-(void)presentFailedView{

    // 跳转至支付失败页面
    LSPayResultVC * LSPayResult = [[LSPayResultVC alloc]init];
    [LSPayResult setCashTypeWithCashFailed];
    [self.navigationController pushViewController:LSPayResult animated:YES];

}

-(void)presentView{
    
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"usertype"] forKey:@"payUserType"];//用户类型 1-个人，2-企业，3-政府
    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"payUserId"];
    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
    [muDicParameters setObject:@(payWay) forKey:@"payWay"];
    [muDicParameters setObject:@(price) forKey:@"payMoney"];
    [muDicParameters setObject:@(1) forKey:@"memberLevel"];
    [muDicParameters setObject:order_no forKey:@"order_no"];
    [muDicParameters setObject:@(orderNumber) forKey:@"orderNumber"];
    
    [self sendRequest:muDicParameters];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.title = @"购买会员";
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 190, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = @"购买会员";
    titleLabel.textColor = RGB(45, 45, 45);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    
    //设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"返回" highImage:@"返回"];
    self.navigationItem.leftBarButtonItem = leftItem;
    NSMutableDictionary * dic = [NSMutableDictionary  dictionary];
    dic[@"token"] = allConstMemberToken;
    dic[@"userId"] = allConstMemberid;
    
    
    [LSHttpTool sendHttpData:@"getUserBalance_app_pay.im.lensum" params:dic success:^(id responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        NSString * balanceStr = [YZBase64 textFromBase64String:dicInfo[@"data"][@"balance"]];
        balanceLabel = [balanceStr floatValue];
        self.balanceLabel.text = [NSString stringWithFormat:@"￥%.2f",[balanceStr floatValue]];
        
    } failure:^(NSError *error) {

        [self showSingleIconBubble:@"网络错误，余额无法显示"];
    }];
    
    self.balanceView.layer.masksToBounds = YES;
    self.balanceView.layer.cornerRadius = 5.0f;
    
    self.payBtn.layer.masksToBounds = YES;
    self.payBtn.layer.cornerRadius = 5.0f;
    
    self.cashLabel.text = @"60.00元";
    price = 60.0f;
    productBody = @"3个月";
    
    [self sendRequestWithGetUserLevelMoneyControl];
    
    
    self.scrollView.backgroundColor = RGB(247.0, 247.0, 247.0);
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;

}
-(void)leftBarButtonItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)setBtn{

    for (int i = 0 ; i <_dataArr.count; i++) {
        UIButton * btn = [[LSCustomBtn alloc]initWithFrame:CGRectMake(i%4*screenW/4 + 2.5, 50, 75, 75)];
        btn.tag = i;
        
        UILabel * timingLabel = btn.subviews[0];
        timingLabel.text = _dataArr[i][@"timing"];
        
        UILabel * moneyLabel = btn.subviews[1];
        moneyLabel.text = [NSString stringWithFormat:@"%@",_dataArr[i][@"money"]];
        
        if (i == 2) {
            self.selectedBtn = btn;
            [self.selectedBtn setBackgroundColor:self.scrollView.backgroundColor];
            btn.layer.borderColor = [UIColor orangeColor].CGColor;
            timingLabel.textColor = [UIColor orangeColor];
            moneyLabel.textColor = [UIColor orangeColor];
            self.moneyLabel = moneyLabel;
            
            orderNumber = 6;
        }
        
        [btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.scrollView addSubview:btn];
    }

}

- (void)clickBtn:(UIButton *)button{
    if(button!=self.selectedBtn){
        
        self.selectedBtn.layer.borderColor = [UIColor whiteColor].CGColor;
         [self.selectedBtn setBackgroundColor:[UIColor whiteColor]];
        
        UILabel * timingLabel = self.selectedBtn.subviews[0];
        timingLabel.textColor = [UIColor lightGrayColor];
        
        UILabel * moneyLabel = self.selectedBtn.subviews[1];
        moneyLabel.textColor = [UIColor lightGrayColor];
        
        self.moneyLabel = moneyLabel;
        self.selectedBtn.selected=NO;
        self.selectedBtn=button;
        
    }
    self.selectedBtn.layer.borderColor = [UIColor orangeColor].CGColor;
     [self.selectedBtn setBackgroundColor:self.scrollView.backgroundColor];
    
    UILabel * timingLabel = self.selectedBtn.subviews[0];
    timingLabel.textColor = [UIColor orangeColor];
    
    UILabel * moneyLabel = self.selectedBtn.subviews[1];
    moneyLabel.textColor = [UIColor orangeColor];
    
    self.moneyLabel = moneyLabel;
    productBody = timingLabel.text;
    self.selectedBtn.selected=YES;
    
    NSDictionary * dict = _dataArr[button.tag];
    price = [dict[@"money"] floatValue];
    
    self.cashLabel.text = [NSString stringWithFormat:@"%@",self.moneyLabel.text];

    switch (button.tag) {
        case 0:
            orderNumber = 1;
            break;
            
        case 1:
            orderNumber = 3;
            break;
            
        case 2:
            orderNumber = 6;
            break;
            
        case 3:
            orderNumber = 12;
            break;
            
        default:
            break;
    }
}

//点击余额购买
- (IBAction)balanceBtn:(UIButton *)sender {
    
    if (balanceLabel < [self.moneyLabel.text floatValue]) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付失败"
                                                        message:@"余额不足！"
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"立刻充值",nil];
        alert.tag = 10;
        [alert show];
        
    }else{
    
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"余额支付" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        
        UITextField *title = [alert textFieldAtIndex:0];
        [title setSecureTextEntry:YES];
        title.borderStyle = UITextBorderStyleNone;
        title.textColor = [UIColor redColor];
        title.textAlignment = NSTextAlignmentCenter;
        title.font = [UIFont systemFontOfSize:16.0f];
        title.placeholder = @"请输入支付密码";
        
        
        [alert showAlertWithCompletionHandler:^(NSInteger buttonIndex) {
            if(buttonIndex == 1){
                UITextField *tf=[alert textFieldAtIndex:0];
                if (tf.text.length > 0) {
                    
                    payWay = 1;
                    
                    [self showRoundProgressWithTitle:@"请稍后..."];
                    
                    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
                    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"usertype"] forKey:@"payUserType"];//用户类型 1-个人，2-企业，3-政府
                    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"payUserId"];
                    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
                    [muDicParameters setObject:@(payWay) forKey:@"payWay"];
                    [muDicParameters setObject:@(price) forKey:@"payMoney"];
                    [muDicParameters setObject:@(1) forKey:@"memberLevel"];
                    [muDicParameters setObject:@(orderNumber) forKey:@"orderNumber"];
                    [muDicParameters setObject:tf.text forKey:@"payPass"];
                    
                    [self sendRequest:muDicParameters];
                    
                }else{
                    
                    NSString *strMsg = @"密码不能为空";
                    
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:strMsg delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
                    [alert show];
                    
                }
            }
        }];
        
        
    
    }
    
}

//点击支付宝购买
- (IBAction)payBtn:(UIButton *)sender {
    
//    if (self.moneyLabel) {
//        price = [self.moneyLabel.text floatValue];
//    }
    
//    price = 0.01;
    payWay = 2;

   order_no = [LSAlipay alipay:@"乐商会员" body:[NSString stringWithFormat:@"乐商网%@会员",productBody] price:price];
    
}

#pragma mark - alertview

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1){
        //充值
        LSRechargeVC * LSRecharge = [[LSRechargeVC alloc]init];
        
        switch (alertView.tag) {
            case 10:
                
              [self.navigationController pushViewController:LSRecharge animated:YES];
                
                break;
                
            default:
                break;
        }
    
    }
}

-(void)sendRequestWithGetUserLevelMoneyControl{

    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"usertype"] forKey:@"userType"];//用户类型 1-个人，2-企业，3-政府
    [muDicParameters setObject:@"1" forKey:@"level"];
    
    [LSHttpTool sendHttpData:@"getUserLevelMoneyControl_app_pay.im" params:muDicParameters success:^(id responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            double levelMoneyWith3 = [dicInfo[@"data"][@"monthMoney"] floatValue] *3;
            double levelMoneyWith6 = [dicInfo[@"data"][@"monthMoney"] floatValue] *6;
            
            _dataArr = @[
                         @{@"timing":@"1个月",@"money":[NSString stringWithFormat:@"%.2f元",[dicInfo[@"data"][@"monthMoney"] floatValue]]},
                         @{@"timing":@"3个月",@"money":[NSString stringWithFormat:@"%.2f元",levelMoneyWith3]},
                         @{@"timing":@"6个月",@"money":[NSString stringWithFormat:@"%.2f元",levelMoneyWith6]},
                         @{@"timing":@"12个月",@"money":[NSString stringWithFormat:@"%.2f元",[dicInfo[@"data"][@"yearMoney"] floatValue]]},
                         ];
            
            [self setBtn];
            
        }else{

            [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];
            
        }
    } failure:^(NSError *error) {

       [self showSingleIconBubble:error.localizedDescription];
        
    }];

}

-(void)sendRequest:(NSDictionary *)dict{

    
    [LSHttpTool sendHttpData:@"rechargeMember_app_pay.im.lensum" params:dict success:^(id responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
        
            // 跳转至支付成功页面
            LSPayResultVC * LSPayResult = [[LSPayResultVC alloc]init];
            [LSPayResult setCashTypeWithCashSuccess];
            [self.navigationController pushViewController:LSPayResult animated:YES];
        
        }else{
            
            // 跳转至支付失败页面
            LSPayResultVC * LSPayResult = [[LSPayResultVC alloc]init];
            [LSPayResult setCashTypeWithCashFailed];
            [self.navigationController pushViewController:LSPayResult animated:YES];

           [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];
        
        }
    } failure:^(NSError *error) {

        [self showSingleIconBubble:error.localizedDescription];
        
    }];

}

@end
